<?php
/**
 * Created by PhpStorm.
 * User: zcq
 * Date: 2019/9/9
 * Time: 9:35
 */

namespace app\admin\controller;


use think\Db;

class Sys extends Base
{
    public $table = 'site_config';
    public function __construct()
    {
        parent::__construct();
    }

    public function index()
    {
        $data = Db::name($this->table)->where('site_id', $this->site_id)->find();

        if(!request()->isPost()){
            $this->assign('data',$data);
            return $this->fetch();
        }else{

            $model = [
                'app_name'=> input('app_name'),
                'app_download_url'=> input('app_download_url'),
                'app_ua'=> input('app_ua'),
                'app_login_api'=> input('app_login_api'),
                'logo'=> input('logo'),
                'modtime'=> time(),
            ];

            if($data){
                $a = Db::name($this->table)->where('id',$data['id'])->update($model);
            }else{
                $model['addtime'] =  time();
                $model['site_id'] = $this->site_id;
                $a = Db::name($this->table)->insert($model);
            }
            if($a){
//                $this->saveConfig();
//                $this->success('保存成功');
                $data = Db::name($this->table)->where('site_id', $this->site_id)->find();
                $this->assign('data',$data);
            }else{
                $this->error('保存失败');
            }
        }
        return $this->fetch();
    }

    private function saveConfig()
    {
        $config = Db::name($this->table)->where('site_id',$this->site_id)->find();
        $data = [];

        foreach ($config as $k=>$v)
        {
            if($k =='addtime' || $k =='modtime' || $k =='id'){
                continue;
            }
            $data[$k] = $v;
        }
        //生成配置文件
        $config_file = APP_PATH . 'extra/sys_'.$this->site_id.'.php';
        create_file ( $config_file );
        arr2file ( $config_file, $data );
    }
}